package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.TimeUtil;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.activities.fragment.dialog.SelectCityDialogFragment;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.ProvinceInfo;
import com.xiaocz.hblsubstitutedriving.model.SGInfo;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.utils.AppUtil;
import com.xiaocz.hblsubstitutedriving.widget.ClearTextIconEditText;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Time:2019/6/22
 * Created by xiaocz
 * Describe 司机认证身份
 */
public class AuthenticationActivity extends BaseActivity implements SelectCityDialogFragment.OnUpdateListener {

    @BindView(R.id.ed_name)
    ClearTextIconEditText edName;
    @BindView(R.id.et_identity_card)
    ClearTextIconEditText edIdentityCard;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_sg)
    TextView tvSg;

    private ProvinceInfo data;

    @Override
    protected void initData() {
        super.initData();
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        if (info != null) {
            edName.setText(info.getTruename());
            edIdentityCard.setText(info.getIdnum());
            if ("选择性别".equals(info.getSex())) {
                tvSex.setHint(info.getSex());
            } else {
                tvSex.setText(info.getSex());
            }
            tvDate.setText(info.getDrivingLicenseTime());
            tvCity.setText(info.getCity_name());
            tvSg.setText(info.getSiguan_name());
            provinceAreaid = info.getProvince_areaid();
            cityId = info.getCity_areaid();
            sgId = info.getSiguan_id();
            tvSg.setHint("0".equals(info.getSiguan_id()) ? "选择司管团队" : info.getSiguan_id());
        }
    }

    private int isSG=0;
    @OnCheckedChanged({R.id.check_box})
    public void OnCheckedChangeListener(CompoundButton view, boolean isCheck) {
        switch (view.getId()) {
            case R.id.check_box:
                isSG=1;
                break;
        }
    }

    private void isCheckValue() {
        String name = String.valueOf(edName.getText());
        if ("".equals(name)) {
            App.getInstance().showMessage("姓名不能为空！");
            return;
        }
        String etIdentityCardValue = String.valueOf(edIdentityCard.getText());
        if ("".equals(etIdentityCardValue) || etIdentityCardValue.length() < 18) {
            App.getInstance().showMessage("身份证号码不符合要求");
            return;
        }
        String dateValue = String.valueOf(tvDate.getText());
        if ("".equals(dateValue)) {
            App.getInstance().showMessage("请选择驾驶证领证日期！");
            return;
        }
        String sexValue = String.valueOf(tvSex.getText()).replace("女", "1").replace("男", "2").replace("选择性别", "");
        if ("0".equals(sexValue)) {
            App.getInstance().showMessage("请选择性别！");
            return;
        }
        String cityValue = String.valueOf(tvCity.getText());
        if ("".equals(cityValue)) {
            App.getInstance().showMessage("请选择城市！");
            return;
        }
        String sgValue = String.valueOf(tvSg.getHint());
        if ("司管人员".equals(sgValue)) {
            sgValue = "0";
        }
        if ("0".equals(sgValue) && "选择司管团队".equals(sgValue)) {
            App.getInstance().showMessage("请选择司管团队！");
            return;
        }
        if (data != null) {
            provinceAreaid = data.getParentId();
            cityId = data.getId();
        }
        sgId = sgValue;
        webPerfection(name, etIdentityCardValue, dateValue, sexValue, provinceAreaid, cityId, sgId);
    }

    private String provinceAreaid, cityId, sgId;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_authentication;
    }

    public static void show(Context context) {
        Intent intent = new Intent(context, AuthenticationActivity.class);
        context.startActivity(intent);
    }

    @OnClick({R.id.tv_city, R.id.tv_date, R.id.tv_sex, R.id.tv_sg, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_city:
                showUpdateDialogFragment(false);
                break;
            case R.id.tv_date:
                hideKeyboard();
                setTime();
                break;
            case R.id.tv_sex:
                hideKeyboard();
                setSex();
                break;
            case R.id.tv_sg://司管
                String cityValue = String.valueOf(tvCity.getText());
                if ("".equals(cityValue)) {
                    App.getInstance().showMessage("请选择城市！");
                    return;
                }
                webSGList(provinceAreaid, cityId);
                break;
            case R.id.btn_submit:
                isCheckValue();
                break;
        }
    }

    /**
     * 获取司管列表
     */
    private void webSGList(String provinceName, String cityName) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("province_areaid", provinceName);
        asyncHttpPostFormData.addFormData("city_areaid", cityName);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/getSiGuanList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<List<SGInfo>>>() {
                }.getType();
                RspModel<List<SGInfo>> rspModel = getAnalysis(response, type, "完善资料");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            if (!"[]".equals(rspModel.getData().toString())) {
                                setSG(rspModel.getData());
                            } else {
                                App.getInstance().showMessage("该区域暂无司管人员！");
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 提交资料
     */
    private void webPerfection(String name, String etIdentityCardValue, String dateValue, String sexValue, String provinceAreaid, String parentId, String sgId) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("truename", name);
        asyncHttpPostFormData.addFormData("idnum", etIdentityCardValue);
        asyncHttpPostFormData.addFormData("drivingLicenseTime", dateValue);
        asyncHttpPostFormData.addFormData("sex", sexValue);
        asyncHttpPostFormData.addFormData("province_areaid", provinceAreaid);
        asyncHttpPostFormData.addFormData("city_areaid", parentId);
        asyncHttpPostFormData.addFormData("siguan_id", sgId);
        asyncHttpPostFormData.addFormData("siguan_status",isSG);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/driverImprovInfo", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<UserInfo>>() {
                }.getType();
                RspModel<UserInfo> rspModel = getAnalysis(response, type, "完善资料");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            App.getInstance().showMessage("信息提交成功，请等待审核！");
                            AppUtil.finishAll();
                            LoginActivity.show(mContext);
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 性别选择
     */
    private void setSex() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择性别");
        final String[] sex = {"男", "女"};
        builder.setItems(sex, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvSex.setText(sex[which]);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 选取司管人员
     */
    private void setSG(final List<SGInfo> list) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择司管人员");
        final String[] sex = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            sex[i] = list.get(i).getTruename() + "-" + list.get(i).getRemarks();
        }
        builder.setItems(sex, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SGInfo info = list.get(which);
                tvSg.setText(String.valueOf(info.getTruename() + "-" + info.getRemarks()));
                tvSg.setHint(info.getId());
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void setTime() {
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if(date.getTime()/1000L-600<=TimeUtil.getLongStamp()){
                    tvDate.setText(TimeUtil.stamp2Time(date, Common.DateType.date));
                }else {
                    App.getInstance().showMessage("请选择正确的时间！");
                }
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).build();
        pvTime.show();
    }

    private void showUpdateDialogFragment(boolean isCheck) {
        SelectCityDialogFragment updateDialogFragment
                = SelectCityDialogFragment.newInstance(this, isCheck);
        if (!updateDialogFragment.isAdded()) {
            updateDialogFragment.show(getSupportFragmentManager(),
                    updateDialogFragment.getClass().getName());
        }
    }

    @Override
    public void returnValue(ProvinceInfo info) {
        data = info;
        provinceAreaid = data.getParentId();
        cityId = data.getId();
        tvSg.setHint("司管人员");
        tvSg.setText("");
        tvCity.setText(info.getName());
    }

    @Override
    public void returnListValue(List<ProvinceInfo> list) {

    }
}
